#include "BitEditor.h"

#define BOXES_PER_ROW 32

BitEditor::BitEditor(BitArray *array, bool editable, QWidget *parent) :
    QWidget(parent), mArray(array), mEditable(editable)
{
    QHBoxLayout *hLayout = new QHBoxLayout(this);
    mGridLayout = new QGridLayout();
    hLayout->addLayout(mGridLayout);
    hLayout->insertStretch(-1);
    hLayout->setContentsMargins(0, 0, 0, 0);
    mGridLayout->setContentsMargins(0, 0, 0, 0);

}

void BitEditor::updateBoxes()
{
    // Number of boxes at least equals array size
    if(mArray->size() == mBoxes.size())
    {
        // Show all existing boxes
        for(int i = 0; i < mBoxes.size(); i++)
        {
            mLabels[i]->show();
            mBoxes[i]->show();
        }
        return;
    }

    // Too many boxes
    if(mArray->size() < mBoxes.size())
    {
        // Hide unneeded boxes
        for(int i = 0; i < mBoxes.size(); i++)
        {
            if(i < mArray->size())
            {
                mLabels[i]->show();
                mBoxes[i]->show();
            }
            else
            {
                mLabels[i]->hide();
                mBoxes[i]->hide();
            }
        }
        return;
    }

    // Too few boxes
    if(mArray->size() > mBoxes.size())
    {
        // Show all existing boxes
        for(int i = 0; i < mBoxes.size(); i++)
        {
            mLabels[i]->show();
            mBoxes[i]->show();
        }
        // Create new boxes
        for(int i = mBoxes.size(); i < mArray->size(); i++)
        {
            QLabel *lb = new QLabel(QString::number(i));
            QCheckBox *cb = new QCheckBox();//QString::number(i));
            if(!(i%8))
            {
                //cb->setText(" ");
                cb->setText(QString::number(i/8));
            }
            cb->setEnabled(mEditable);
            mGridLayout->addWidget(lb, 2*(i/BOXES_PER_ROW), BOXES_PER_ROW-(i%BOXES_PER_ROW)-1);
            mGridLayout->addWidget(cb, 2*(i/BOXES_PER_ROW)+1, BOXES_PER_ROW-(i%BOXES_PER_ROW)-1);
            mLabels.append(lb);
            mBoxes.append(cb);
            connect(cb, SIGNAL(clicked()), this, SLOT(cBoxChangedSlot()));
        }
    }
}

 void BitEditor::updateView()
 {
     if(!this->isVisible())
         return;
      this->hide();
      updateBoxes();
      for(int i = 0; i < mArray->size(); i++)
      {
          mBoxes[i]->setChecked(mArray->at(i));
      }
      this->show();
 }

 void BitEditor::cBoxChangedSlot()
 {
     for(int i = 0; i < mArray->size(); i++)
     {
         mArray->setBit(i, mBoxes[i]->isChecked());
     }
     emit valueChanged();
 }
